﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bukovics.Workflow.Hosting;
using System.Workflow.Runtime.Hosting;
using SharedWorkflows;
using System.Workflow.Runtime;
using System.Workflow.Activities;

namespace WinformTest
{
    public partial class Default : Form
    {
        //private WorkflowRuntimeManager _workflowManager;
        //private WorkflowPersistenceService _persistence;
        //private BillServer _billServer;
        //private Dictionary<Guid, Workflow> _workflows
        //    = new Dictionary<Guid, Workflow>();

        public Default()
        {
            InitializeComponent();
        }

        private void ShowControls()
        {
            String sql = "select name from system_dutys where id=" + GlobleVar.mySelf.duty_id;
            string[][] tmpdata=CommonLibrary.DB.DBExecuteUtil.querySqlArray(sql);
            string dutyname = tmpdata[0][0];
            if (dutyname == "财务")
                linkLabel_f.Visible = true;
            else if (dutyname == "老板")
                linkLabel_b.Visible = true;
            else if (dutyname == "出纳")
                linkLabel_p.Visible = true;
            linkLabel_g.Visible = true;
        }

        #region Initialization and shutdown
        /// <summary>
        /// Initialize the workflow runtime during startup
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //create workflow runtime and manager
            GlobleVar._workflowManager = new WorkflowRuntimeManager(
                new WorkflowRuntime());
            //add services to the workflow runtime
            AddServices(GlobleVar._workflowManager.WorkflowRuntime);

            ShowControls();

            GlobleVar._workflowManager.WorkflowRuntime.WorkflowCreated
                += new EventHandler<WorkflowEventArgs>(
                    WorkflowRuntime_WorkflowCreated);
            GlobleVar._workflowManager.WorkflowRuntime.WorkflowCompleted
                += new EventHandler<WorkflowCompletedEventArgs>(
                    WorkflowRuntime_WorkflowCompleted);
            GlobleVar._workflowManager.WorkflowRuntime.WorkflowPersisted
                += new EventHandler<WorkflowEventArgs>(
                    WorkflowRuntime_WorkflowPersisted);
            GlobleVar._workflowManager.WorkflowRuntime.WorkflowUnloaded
                += new EventHandler<WorkflowEventArgs>(
                    WorkflowRuntime_WorkflowUnloaded);
            GlobleVar._workflowManager.WorkflowRuntime.WorkflowLoaded
                += new EventHandler<WorkflowEventArgs>(
                    WorkflowRuntime_WorkflowLoaded);
            GlobleVar._workflowManager.WorkflowRuntime.WorkflowIdled
                += new EventHandler<WorkflowEventArgs>(
                    WorkflowRuntime_WorkflowIdled);

            //start the runtime prior to checking for any
            //existing workflows that have been persisted
            GlobleVar._workflowManager.WorkflowRuntime.StartRuntime();
        }

        /// <summary>
        /// Add any services needed by the runtime engine
        /// </summary>
        /// <param name="instance"></param>
        private void AddServices(WorkflowRuntime instance)
        {
            //use the standard SQL Server persistence service
            String connStringPersistence = String.Format(
                "Initial Catalog={0};Data Source={1};Integrated Security={2};",
                "SqlPersistenceService", @"localhost\SQL2005", "SSPI");
            GlobleVar._persistence =
                new SqlWorkflowPersistenceService(connStringPersistence, true,
                    new TimeSpan(0, 2, 0), new TimeSpan(0, 0, 5));
            instance.AddService(GlobleVar._persistence);

            //add the external data exchange service to the runtime
            ExternalDataExchangeService exchangeService
                = new ExternalDataExchangeService();
            instance.AddService(exchangeService);

            //add our local service 
            GlobleVar._billServer = new BillServer();
            exchangeService.AddService(GlobleVar._billServer);
        }

        /// <summary>
        /// Perform cleanup during application shutdown 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            //cleanup the workflow runtime
            if (GlobleVar._workflowManager != null)
            {
                GlobleVar._workflowManager.Dispose();
            }
        }

        #endregion

        #region UIevent

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            WorkflowInstanceWrapper wfiw = GlobleVar._workflowManager.StartWorkflow(typeof(给叶老看看), null);
            CreateBill cb = new CreateBill(wfiw.Id);
            cb.ShowDialog();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Boss b = new Boss();
            b.ShowDialog();
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Finance f = new Finance();
            f.ShowDialog();
        }

        private void linkLabel4_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            PayBox pb = new PayBox();
            pb.ShowDialog();
        }

        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OutMoney om = new OutMoney();
            om.ShowDialog();
        }
        private void SetButtonState()
        {
            //if (_selectedWorkflow != null)
            //{
            //    btnContinue.Enabled = !(_selectedWorkflow.IsCompleted);
            //    btnStop.Enabled = !(_selectedWorkflow.IsCompleted);
            //}
            //else
            //{
            //    btnContinue.Enabled = false;
            //    btnStop.Enabled = false;
            //}
        }
        #endregion

        #region Workflow event handling

        void WorkflowRuntime_WorkflowCreated(object sender,
            WorkflowEventArgs e)
        {
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Created");
        }

        void WorkflowRuntime_WorkflowIdled(object sender,
            WorkflowEventArgs e)
        {
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Idled");
        }

        void WorkflowRuntime_WorkflowLoaded(object sender,
            WorkflowEventArgs e)
        {
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Loaded");
        }

        void WorkflowRuntime_WorkflowUnloaded(object sender,
            WorkflowEventArgs e)
        {
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Unloaded");
        }

        void WorkflowRuntime_WorkflowPersisted(object sender,
            WorkflowEventArgs e)
        {
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Persisted");
        }

        void WorkflowRuntime_WorkflowCompleted(object sender,
            WorkflowCompletedEventArgs e)
        {
            UpdateCompletedWorkflow(e.WorkflowInstance.InstanceId);
            UpdateDisplay(e.WorkflowInstance.InstanceId, "Completed");
        }

        private delegate void UpdateDelegate();

        private void UpdateDisplay(Guid instanceId, String statusMessage)
        {
            UpdateDelegate theDelegate = delegate()
            {
                Workflow workflow = GetWorkflow(instanceId);
                workflow.StatusMessage = statusMessage;
                //RefreshData();
                //slow things down so you can see the status changes
                System.Threading.Thread.Sleep(1000);
                SetButtonState();
            };

            //execute the anonymous delegate on the UI thread
            this.Invoke(theDelegate);
            Console.ForegroundColor=ConsoleColor.Green;
            Console.WriteLine("{0} is {1}", instanceId, statusMessage);
        }

        private void UpdateCompletedWorkflow(Guid instanceId)
        {
            UpdateDelegate theDelegate = delegate()
            {
                Workflow workflow = GetWorkflow(instanceId);
                workflow.IsCompleted = true;
            };

            //execute the anonymous delegate on the UI thread
            this.Invoke(theDelegate);
        }

        private Workflow GetWorkflow(Guid instanceId)
        {
            Workflow result = null;
            if (GlobleVar._workflows.ContainsKey(instanceId))
            {
                result = GlobleVar._workflows[instanceId];
            }
            else
            {
                //create a new instance
                result = new Workflow();
                result.InstanceId = instanceId;
                GlobleVar._workflows.Add(result.InstanceId, result);
            }
            return result;
        }
        #endregion
    }
}
